import * as crypto from "crypto";

let nonce = 0;

//从input生成SHA-256 hash值
async function generateHash(input) {
  const msgBuffer = new TextEncoder().encode(input); //编码为UTF-8
  const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer); //hash消息
  const hashArray = Array.from(new Uint8Array(hashBuffer)); //将hashBuffer转换为数组
  const hashHex = hashArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join(""); //将数组转换为16进制字符串
  return hashHex;
}

//将随机数加到input后计算hash值
async function calculateHashWithNonce(nonce) {
  const data = "Hello World" + nonce;
  return generateHash(data);
}

//从随机数中找出符合条件（hash值开头为0000）的nonce值
async function myNonce() {
  let hash;
  do {
    hash = await calculateHashWithNonce(++nonce);
  } while (hash.startsWith("0000") === false);
  console.log(`Nonce: ${nonce}, hash: ${hash}`);
}

//测试
myNonce();
